<template>
  <div class="security-container">
    <div class="page-header">
      <el-button @click="goBack" text>
        <el-icon><ArrowLeft /></el-icon>
        返回个人中心
      </el-button>
      <h1>安全设置</h1>
      <p>管理您的账户安全和隐私设置</p>
    </div>

    <div class="security-sections">
      <!-- 密码设置 -->
      <el-card class="security-card">
        <template #header>
          <div class="card-header">
            <el-icon><Lock /></el-icon>
            <h3>密码设置</h3>
          </div>
        </template>

        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="120px"
          class="password-form"
        >
          <el-form-item label="当前密码" prop="currentPassword">
            <el-input
              v-model="passwordForm.currentPassword"
              type="password"
              placeholder="请输入当前密码"
              show-password
            />
          </el-form-item>

          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码"
              show-password
            />
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              show-password
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="updatePassword" :loading="passwordLoading">
              更新密码
            </el-button>
            <el-button @click="resetPasswordForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 登录安全 -->
      <el-card class="security-card">
        <template #header>
          <div class="card-header">
            <el-icon><Setting /></el-icon>
            <h3>登录安全</h3>
          </div>
        </template>

        <div class="security-options">
          <div class="security-item">
            <div class="security-info">
              <h4>双因素认证</h4>
              <p>为您的账户增加额外的安全保护</p>
            </div>
            <el-switch
              v-model="securitySettings.twoFactorEnabled"
              @change="toggleTwoFactor"
              :loading="twoFactorLoading"
            />
          </div>

          <div class="security-item">
            <div class="security-info">
              <h4>登录通知</h4>
              <p>新设备登录时通过邮件通知您</p>
            </div>
            <el-switch
              v-model="securitySettings.loginNotification"
              @change="toggleLoginNotification"
            />
          </div>

          <div class="security-item">
            <div class="security-info">
              <h4>自动登出</h4>
              <p>长时间无操作时自动退出登录</p>
            </div>
            <el-select v-model="securitySettings.autoLogoutTime" @change="updateAutoLogout">
              <el-option label="30分钟" :value="30" />
              <el-option label="1小时" :value="60" />
              <el-option label="2小时" :value="120" />
              <el-option label="永不" :value="0" />
            </el-select>
          </div>
        </div>
      </el-card>

      <!-- 区块链设置 -->
      <el-card class="security-card">
        <template #header>
          <div class="card-header">
            <el-icon><Link /></el-icon>
            <h3>区块链设置</h3>
          </div>
        </template>

        <div class="blockchain-settings">
          <div class="blockchain-item">
            <div class="blockchain-info">
              <h4>以太坊地址</h4>
              <p>您的区块链身份标识</p>
            </div>
            <div class="blockchain-value">
              <el-input
                v-model="blockchainSettings.ethereumAddress"
                placeholder="0x..."
                :disabled="!editingAddress"
                class="address-input"
              />
              <el-button
                v-if="!editingAddress"
                @click="editingAddress = true"
                text
                type="primary"
              >
                编辑
              </el-button>
              <div v-else>
                <el-button @click="updateEthereumAddress" type="primary" size="small">
                  保存
                </el-button>
                <el-button @click="cancelEditAddress" size="small">
                  取消
                </el-button>
              </div>
            </div>
          </div>

          <div class="blockchain-item">
            <div class="blockchain-info">
              <h4>私钥管理</h4>
              <p>安全存储您的私钥信息</p>
            </div>
            <el-button @click="showPrivateKeyDialog = true" type="warning">
              管理私钥
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 登录历史 -->
      <el-card class="security-card">
        <template #header>
          <div class="card-header">
            <el-icon><Clock /></el-icon>
            <h3>登录历史</h3>
          </div>
        </template>

        <el-table :data="loginHistory" style="width: 100%">
          <el-table-column prop="time" label="登录时间" width="180" />
          <el-table-column prop="ip" label="IP地址" width="150" />
          <el-table-column prop="location" label="位置" />
          <el-table-column prop="device" label="设备" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
                {{ row.status === 'success' ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 私钥管理对话框 -->
    <el-dialog
      v-model="showPrivateKeyDialog"
      title="私钥管理"
      width="500px"
      :before-close="handlePrivateKeyClose"
    >
      <el-alert
        title="安全提醒"
        type="warning"
        :closable="false"
        style="margin-bottom: 20px;"
      >
        私钥是您区块链身份的重要凭证，请妥善保管，不要泄露给他人。
      </el-alert>

      <el-form>
        <el-form-item label="当前私钥状态">
          <el-tag :type="hasPrivateKey ? 'success' : 'warning'">
            {{ hasPrivateKey ? '已设置' : '未设置' }}
          </el-tag>
        </el-form-item>

        <el-form-item label="新私钥" v-if="!hasPrivateKey">
          <el-input
            v-model="privateKeyForm.privateKey"
            type="password"
            placeholder="请输入私钥（64位十六进制）"
            show-password
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showPrivateKeyDialog = false">取消</el-button>
        <el-button type="danger" v-if="hasPrivateKey" @click="removePrivateKey">
          移除私钥
        </el-button>
        <el-button type="primary" v-else @click="savePrivateKey" :disabled="!privateKeyForm.privateKey">
          保存私钥
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { apiMethods } from '@/api'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, 
  Lock, 
  Setting,
  Link, 
  Clock 
} from '@element-plus/icons-vue'

const router = useRouter()
const authStore = useAuthStore()

// 状态
const passwordFormRef = ref()
const passwordLoading = ref(false)
const twoFactorLoading = ref(false)
const editingAddress = ref(false)
const showPrivateKeyDialog = ref(false)

// 表单数据
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const securitySettings = reactive({
  twoFactorEnabled: false,
  loginNotification: true,
  autoLogoutTime: 60
})

const blockchainSettings = reactive({
  ethereumAddress: '',
  originalAddress: ''
})

const privateKeyForm = reactive({
  privateKey: ''
})

// 登录历史数据
const loginHistory = ref([
  {
    time: '2024-08-27 14:30:25',
    ip: '192.168.1.100',
    location: '中国 浙江 杭州',
    device: 'Chrome 119 on Windows 10',
    status: 'success'
  },
  {
    time: '2024-08-26 09:15:42',
    ip: '192.168.1.100',
    location: '中国 浙江 杭州',
    device: 'Chrome 119 on Windows 10',
    status: 'success'
  },
  {
    time: '2024-08-25 16:22:18',
    ip: '192.168.1.101',
    location: '中国 浙江 杭州',
    device: 'Safari on iPhone',
    status: 'success'
  }
])

// 计算属性
const hasPrivateKey = ref(false)

// 验证规则
const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 方法
const goBack = () => {
  router.push('/profile')
}

const updatePassword = async () => {
  if (!passwordFormRef.value) return

  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true

    const response = await apiMethods.user.updatePassword({
      currentPassword: passwordForm.currentPassword,
      newPassword: passwordForm.newPassword
    })

    if (response.data.success) {
      ElMessage.success('密码更新成功')
      resetPasswordForm()
    }
  } catch (error) {
    console.error('更新密码失败:', error)
    ElMessage.error('更新密码失败，请检查当前密码是否正确')
  } finally {
    passwordLoading.value = false
  }
}

const resetPasswordForm = () => {
  passwordForm.currentPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordFormRef.value?.clearValidate()
}

const toggleTwoFactor = async (enabled) => {
  twoFactorLoading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success(`双因素认证已${enabled ? '启用' : '禁用'}`)
  } catch (error) {
    securitySettings.twoFactorEnabled = !enabled
    ElMessage.error('操作失败，请重试')
  } finally {
    twoFactorLoading.value = false
  }
}

const toggleLoginNotification = (enabled) => {
  ElMessage.success(`登录通知已${enabled ? '启用' : '禁用'}`)
}

const updateAutoLogout = (time) => {
  const timeText = time === 0 ? '永不' : `${time}分钟`
  ElMessage.success(`自动登出时间已设置为${timeText}`)
}

const updateEthereumAddress = async () => {
  try {
    // 验证以太坊地址格式
    if (!/^0x[a-fA-F0-9]{40}$/.test(blockchainSettings.ethereumAddress)) {
      ElMessage.error('请输入有效的以太坊地址')
      return
    }

    // 调用API更新地址
    const response = await apiMethods.user.updateEthereumAddress({
      address: blockchainSettings.ethereumAddress
    })

    if (response.data.success) {
      ElMessage.success('以太坊地址更新成功')
      blockchainSettings.originalAddress = blockchainSettings.ethereumAddress
      editingAddress.value = false
    }
  } catch (error) {
    console.error('更新以太坊地址失败:', error)
    ElMessage.error('更新失败，请重试')
  }
}

const cancelEditAddress = () => {
  blockchainSettings.ethereumAddress = blockchainSettings.originalAddress
  editingAddress.value = false
}

const handlePrivateKeyClose = (done) => {
  privateKeyForm.privateKey = ''
  done()
}

const savePrivateKey = async () => {
  try {
    // 验证私钥格式
    if (!/^[a-fA-F0-9]{64}$/.test(privateKeyForm.privateKey)) {
      ElMessage.error('请输入有效的私钥（64位十六进制）')
      return
    }

    await ElMessageBox.confirm(
      '私钥将被加密存储，确定要保存吗？',
      '确认保存',
      { type: 'warning' }
    )

    // 模拟保存私钥
    hasPrivateKey.value = true
    showPrivateKeyDialog.value = false
    ElMessage.success('私钥保存成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('保存私钥失败')
    }
  }
}

const removePrivateKey = async () => {
  try {
    await ElMessageBox.confirm(
      '移除私钥后将无法进行区块链交易，确定要移除吗？',
      '确认移除',
      { type: 'warning' }
    )

    hasPrivateKey.value = false
    showPrivateKeyDialog.value = false
    ElMessage.success('私钥已移除')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('移除私钥失败')
    }
  }
}

// 生命周期
onMounted(() => {
  // 加载用户安全设置
  const user = authStore.user
  if (user) {
    blockchainSettings.ethereumAddress = user.address || ''
    blockchainSettings.originalAddress = user.address || ''
    hasPrivateKey.value = !!user.hasPrivateKey
  }
})
</script>

<style scoped>
.security-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  color: #2c3e50;
  margin: 10px 0;
}

.page-header p {
  color: #606266;
  font-size: 14px;
}

.security-sections {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.security-card {
  width: 100%;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-header h3 {
  margin: 0;
  color: #2c3e50;
}

.password-form {
  max-width: 400px;
}

.security-options {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 24px;
  border-bottom: 1px solid #ebeef5;
}

.security-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.security-info h4 {
  margin: 0 0 4px 0;
  color: #2c3e50;
  font-size: 16px;
}

.security-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.blockchain-settings {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.blockchain-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding-bottom: 24px;
  border-bottom: 1px solid #ebeef5;
}

.blockchain-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.blockchain-info h4 {
  margin: 0 0 4px 0;
  color: #2c3e50;
  font-size: 16px;
}

.blockchain-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.blockchain-value {
  display: flex;
  align-items: center;
  gap: 12px;
  max-width: 400px;
}

.address-input {
  width: 300px;
}

@media (max-width: 768px) {
  .security-container {
    padding: 10px;
  }

  .security-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .blockchain-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .blockchain-value {
    width: 100%;
    max-width: none;
  }

  .address-input {
    flex: 1;
    width: auto;
  }
}
</style>